package com.example.administrator.myapplication.biz;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.example.administrator.myapplication.bean.ScoreBean;
import com.example.administrator.myapplication.db.DBHelper;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2016/3/22 0022.
 */
public class ScoreBiz {
    DBHelper mDBHelper;
    public  ScoreBiz(Context context){
        mDBHelper = new DBHelper(context);
    }
    //添加数据
    /*
     * 如果数据多了 用对象来装
     * 如果对象多了 用容器来装
     */
    public long insert(ScoreBean bean) {
        //得到数据库对象
        SQLiteDatabase db = mDBHelper.getWritableDatabase();
        //插入
        ContentValues values = new ContentValues();
        values.put("name", bean.getName());
        values.put("score", bean.getScore());
        values.put("level", bean.getLevel());

        long id = db.insert("score", null, values);

        db.close();
        return id;
    }
    //查询数据
    public List<ScoreBean> query(int level){
        List<ScoreBean> list = new ArrayList<>();
        SQLiteDatabase db = mDBHelper.getWritableDatabase();
        //查询
        Cursor cursor = db.rawQuery("select *from score where level=? order by score desc",new String[]{level+""});
        //组装数据
        while (cursor.moveToNext()) {
            String name = cursor.getString(cursor.getColumnIndex("name"));
            long score = cursor.getLong(cursor.getColumnIndex("score"));
            System.out.println("name=" + name + "level=" + level + "score=" + score);
            ScoreBean bean = new ScoreBean(level,score,name);
            list.add(bean);
        }
        cursor.close();
        db.close();
        return list;
    }
    //查询第10名的成绩
    public ScoreBean queryScoreByLevel(int level)
    {
        ScoreBean bean = null;
        //得到数据库对象
        SQLiteDatabase db = mDBHelper.getWritableDatabase();
        //查询
        Cursor cursor = db.rawQuery("select * from score where level=? order by score asc limit 9,1", new String[]{level+""});
        //如果查到了数据
        if(cursor.moveToNext())
        {
            String name = cursor.getString(cursor.getColumnIndex("name"));
            long score = cursor.getLong(cursor.getColumnIndex("score"));
            bean = new ScoreBean(level, score, name);
        }
        //关闭
        cursor.close();
        db.close();
        return bean;
    }
    //清空所有数据
    public int deleteAll()
    {
        //得到数据库对象
        SQLiteDatabase db = mDBHelper.getWritableDatabase();
        int count = db.delete("score", null, null);
        db.close();
        return count;
    }
}
